package com.fh.shop.api.sms.biz;

import com.alibaba.fastjson.JSON;
import com.fh.shop.api.common.ResponseEnum;
import com.fh.shop.api.common.ServerResponse;
import com.fh.shop.api.common.SystemConst;
import com.fh.shop.api.sms.vo.SMSVo;
import com.fh.shop.api.util.KeyUtil;
import com.fh.shop.api.util.RedisUtil;
import com.fh.shop.api.util.SMSUtil;
import com.fh.shop.api.util.ValidateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service("smsService")
public class ISMSServiceImpl implements ISMSService {

        @Override
        public ServerResponse sendMsg(String phone) {
        // 验证手机号是否为空
        if (StringUtils.isEmpty(phone)) {
        return ServerResponse.error(ResponseEnum.SMS_PHONE_IS_NULL);
        }
        // 验证手机号是否合法【java正则表达式】
        if (!ValidateUtil.isPhone(phone)) {
            return ServerResponse.error(ResponseEnum.MEMBER_REG_PHONE_IS_ERROR);
        }
        // json格式的字符串
        /**
         * {
         *   "code": 200,
         *   "msg": "88",
         *   "obj": "1908"
         * }
         */
        String result = SMSUtil.sendMsg(phone);
        // 将json格式的字符串转为java对象
        SMSVo smsVo = JSON.parseObject(result, SMSVo.class);
        int code = smsVo.getCode();
        if (code == SystemConst.SMS_OK) {
            // 短信验证码
            String obj = smsVo.getObj();
            // 将短信验证码存入redis中，方便后续的对比验证
            RedisUtil.setEx(KeyUtil.buildSMSPhoneKey(phone), obj, SystemConst.SMS_CODE_EXPIRE_TIME);
            return ServerResponse.success();
        } else {
            return ServerResponse.error(-1, "发送短信失败，错误编号:"+code+",具体原因联系管理员！");
        }
    }
}
